package com.sihai.ehr.service.impl;

import com.sihai.core.*;
import com.sihai.ehr.model.biz.Transaction;
import com.sihai.ehr.model.biz.TransactionAuditing;
import com.sihai.ehr.model.biz.Transaction.TransactionType;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.repository.AuditingRepository;
import com.sihai.ehr.service.TransactionService;
import com.sihai.ehr.web.pojo.SearchFormPojo;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;

import java.util.List;

/**
 * author: wxn
 * since: 13-4-8 下午9:33
 */
@Service("transactionService")
public class TransactionServiceImpl implements TransactionService {
    @Resource
    private DataAccessor dataAccessor;
    @Resource
    private AuditingRepository auditingRepository;

    @Override
    public void save(Transaction transaction)throws Exception{
        Assert.notNull(transaction, "transaction is required");
        boolean isCreate = (transaction.getId() == null || transaction.getId() <= 0);
        dataAccessor.save(transaction);
        if(isCreate){
            saveTransactionAuditing(transaction, 1);
        }
    }

    @Override
    public Transaction get(Long id)throws Exception {
        Assert.notNull(id, "transaction id is required");
        return dataAccessor.get(Transaction.class, id);
    }

    @Override
    public boolean delete(String ids) throws Exception{
        final String deleteSql = String.format("delete from Transaction t where t.id in (%s)", ids);
        this.dataAccessor.batchUpdate(new QueryCreator() {
            @Override
            public Query createQuery(Session session) {
                return session.createQuery(deleteSql);
            }
        });
        return true;
    }

    @Override
    public LimitedList<Transaction> findTransaction(Limit limit, Sorter sorter) throws Exception{
        return null;
    }

    @Override
    public LimitedList<Transaction> findTransactionByOrganizationAndType(final Long organizationId, final Transaction.TransactionType type, final SearchFormPojo searchFormPojo, Limit limit, Sorter sorter) throws Exception {
        Assert.notNull(type, "transaction type is required");
        Assert.notNull(organizationId, "organization id is required");
        if(searchFormPojo == null){
            return dataAccessor.findByHql(Transaction.class, "from Transaction t where t.topOrganization.id=? and t.type = ?", new Object[]{organizationId, type}, limit, sorter);
        }
        return dataAccessor.findByQuery(Transaction.class, new QueryCreator(){
            @Override
            public Query createQuery(Session session) {
                DynamicQuery query = new DynamicQuery("from Transaction t where 1=1");
                query.appendIfNotNull("and t.create_date > :startDate","startDate", searchFormPojo.getStartDate());
                query.appendIfNotNull("and t.create_date < :endDate","endDate", searchFormPojo.getEndDate());
                if(searchFormPojo.getOrgId() != null && searchFormPojo.getOrgId() > 0){
                    Organization o = dataAccessor.get(Organization.class, searchFormPojo.getOrgId());
                    if(o != null){
                        query.append("and t.oldOrganization.treePath like '" + o.getTreePath() + "%'");
                    }
                }else{
                    query.append("and t.topOrganization.id=:topOrg", "topOrg", organizationId);
                }
                query.appendIfNotNull("and t.type = :type", "type", type);
                query.appendIfNotNull("and t.oldDuty.id = :dutyId", "dutyId", searchFormPojo.getDutyId());
                return query.build(session);
            }
        }, limit, sorter);
    }
    
    @Override
    public LimitedList<Transaction> findTransactionByWorkIdAndType(final Long workId,
    		final TransactionType type, final SearchFormPojo searchFormPojo, Limit limit,
    		Sorter sorter) throws Exception {
    	 Assert.notNull(type, "transaction type is required");
         Assert.notNull(workId, "workId id is required");
         if(searchFormPojo == null){
             return dataAccessor.findByHql(Transaction.class, "from Transaction t where t.work.id=? and t.type = ?", new Object[]{workId, type}, limit, sorter);
         }
         return dataAccessor.findByQuery(Transaction.class, new QueryCreator(){
             @Override
             public Query createQuery(Session session) {
                 DynamicQuery query = new DynamicQuery("from Transaction t where 1=1");
                 query.appendIfNotNull("and t.create_date > :startDate","startDate", searchFormPojo.getStartDate());
                 query.appendIfNotNull("and t.create_date < :endDate","endDate", searchFormPojo.getEndDate());
                 if(searchFormPojo.getOrgId() != null && searchFormPojo.getOrgId() > 0){
                     Organization o = dataAccessor.get(Organization.class, searchFormPojo.getOrgId());
                     if(o != null){
                         query.append("and t.oldOrganization.treePath like '" + o.getTreePath() + "%'");
                     }
                 }else{
                     query.append("and t.work.id=:workId", "workId", workId);
                 }
                 query.appendIfNotNull("and t.type = :type", "type", type);
                 query.appendIfNotNull("and t.oldDuty.id = :dutyId", "dutyId", searchFormPojo.getDutyId());
                 return query.build(session);
             }
         }, limit, sorter);
    }


    //查询异动审核流程记录
    @Override
    public List<List<TransactionAuditing>> findTransactionAuditing(Long transactionId) {
        return auditingRepository.findByHql(TransactionAuditing.class, "from TransactionAuditing ta where ta.transaction.id = ?", new Object[]{transactionId});
    }


    @Override
    public void saveTransactionAuditingProcess(Long transactionId) {
        saveTransactionAuditing(dataAccessor.get(Transaction.class, transactionId), 1);
    }

    //创建审核流程
    private void saveTransactionAuditing(Transaction transaction, int auditNo) {
        auditingRepository.saveAuditingProcess(transaction, auditNo);
    }
}
